package com.atguigu.app.dws;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.bean.TradeOrderBean;
import com.atguigu.func.MyWindowFunction;
import com.atguigu.uitl.ClickHouseUtil;
import com.atguigu.uitl.MyKafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @author hjy
 * @create 2023/3/17 21:04
 */
public class Dws08_TradeOrderWindow {
    public static void main(String[] args) throws Exception {
        //todo 1 获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
//        env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall-flink/check");
//        env.getCheckpointConfig().setCheckpointTimeout(60000L);
//        env.setStateBackend(new HashMapStateBackend());
//        System.setProperty("HAOOP_USER_NAME","atguigu");
        //todo 2 从kafka（dwd_trade_order_detail）读数据
        String topic="dwd_trade_order_detail";
        String groupID="trade_payment_suc_0926";
        DataStreamSource<String> kafkaDS = env.addSource(MyKafkaUtil.getFlinkKafkaConsumer(topic, groupID));
        //todo 3 过滤null值并将数据转为JSONObj对象
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaDS.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                if (value != null) {
                    out.collect(JSONObject.parseObject(value));
                }
            }
        });

        //todo 4 提取waterMark
        SingleOutputStreamOperator<JSONObject> jsonObjWithWMDS = jsonObjDS.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                .withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
                    @Override
                    public long extractTimestamp(JSONObject element, long recordTimestamp) {
                        return element.getLong("create_time");
                    }
                }));
        //todo 5 按照uid分组
        KeyedStream<JSONObject, String> keyedStream = jsonObjWithWMDS.keyBy(value -> value.getString("user_id"));

        //todo 6 转换为javaBean对象
        SingleOutputStreamOperator<TradeOrderBean> tradeOrderBeanDS = keyedStream.flatMap(new RichFlatMapFunction<JSONObject, TradeOrderBean>() {
            private ValueState<String> lastPayDtState;

            @Override
            public void open(Configuration parameters) throws Exception {
                lastPayDtState = getRuntimeContext().getState(new ValueStateDescriptor<String>("last_pay_dt", String.class));
            }

            @Override
            public void flatMap(JSONObject value, Collector<TradeOrderBean> out) throws Exception {
                String lastDt = lastPayDtState.value();
                String curtDt = value.getString("create_time").split(" ")[0];
                Long uniqueUV = 0L;
                Long newUV = 0L;
                if (lastDt == null) {
                    uniqueUV = 1L;
                    newUV = 1L;
                    lastPayDtState.update(curtDt);
                } else if (!lastDt.equals(curtDt)) {
                    uniqueUV = 1L;
                    lastPayDtState.update(curtDt);
                }
                if (uniqueUV == 1L) {
                    out.collect(new TradeOrderBean("",
                            "",
                            uniqueUV,
                            newUV,
                            null));
                }
            }
        });

        //todo 7 开窗聚合
        SingleOutputStreamOperator<TradeOrderBean> resultDS = tradeOrderBeanDS.windowAll(TumblingEventTimeWindows.of(Time.seconds(10)))
                .reduce(new ReduceFunction<TradeOrderBean>() {
                    @Override
                    public TradeOrderBean reduce(TradeOrderBean value1, TradeOrderBean value2) throws Exception {
                        value1.setOrderUniqueUserCount(value1.getOrderUniqueUserCount() + value2.getOrderUniqueUserCount());
                        value1.setOrderNewUserCount(value1.getOrderNewUserCount() + value2.getOrderNewUserCount());
                        return value1;
                    }
                }, new AllWindowFunction<TradeOrderBean, TradeOrderBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window, Iterable<TradeOrderBean> values, Collector<TradeOrderBean> out) throws Exception {
                        TradeOrderBean next = values.iterator().next();
                        out.collect(MyWindowFunction.getJavaBeanField(next, window));
                    }
                });
        //todo 8 将数据写出到clickHouse
        resultDS.print("resultDS>>>>>>>>>>>>");
        resultDS.addSink(ClickHouseUtil.getSinkFunction("insert into dws_trade_order_window values(?,?,?,?,?)"));

        //todo 9 启动程序
        env.execute("Dws08_TradeOrderWindow");
    }
}
